<template>
  <view>
    <view class="uni-header">
      <view class="uni-group">
        <view class="uni-title"></view>
        <view class="uni-sub-title"></view>
      </view>
      <view class="uni-group">
        <button
          class="uni-button"
          type="default"
          size="mini"
          @click="navigateTo('./add')"
        >
          新增
        </button>
        <button
          class="uni-button"
          type="default"
          size="mini"
          :disabled="!selectedIndexs.length"
          @click="delTable"
        >
          批量删除
        </button>
        <download-excel
          class="hide-on-phone"
          :fields="exportExcel.fields"
          :data="exportExcelData"
          :type="exportExcel.type"
          :name="exportExcel.filename"
        >
          <button class="uni-button" type="primary" size="mini">
            导出 Excel
          </button>
        </download-excel>
      </view>
    </view>
    <view class="uni-container">
      <unicloud-db
        ref="udb"
        :collection="collectionList"
        :where="where"
        page-data="replace"
        :orderby="orderby"
        :getcount="true"
        :page-size="options.pageSize"
        :page-current="options.pageCurrent"
        v-slot:default="{ data, pagination, loading, error, options }"
        :options="options"
        loadtime="manual"
        @load="onqueryload"
      >
        <uni-table
          ref="table"
          :loading="loading"
          :emptyText="error.message || '没有更多数据'"
          border
          stripe
          type="selection"
          @selection-change="selectionChange"
        >
          <uni-tr>
            <uni-th
              v-if="isSuperAdmin"
              align="center"
              sortable
              @sort-change="sortChange($event, 'user_id')"
              >user_id</uni-th
            >
            <uni-th align="center">分类</uni-th>
            <uni-th
              align="center"
              sortable
              @sort-change="sortChange($event, 'avatar')"
              >封面大图</uni-th
            >
            <uni-th
              align="center"
              sortable
              @sort-change="sortChange($event, 'content')"
              >活动详情大图</uni-th
            >
            <uni-th
              align="center"
              filter-type="select"
              :filter-data="options.filterData.article_status_localdata"
              @filter-change="filterChange($event, 'article_status')"
              >状态</uni-th
            >
            <uni-th
              align="center"
              filter-type="search"
              @filter-change="filterChange($event, 'title')"
              sortable
              @sort-change="sortChange($event, 'title')"
              >活动名称</uni-th
            >
            <uni-th
              align="center"
              filter-type="timestamp"
              @filter-change="filterChange($event, 'start_time')"
              sortable
              @sort-change="sortChange($event, 'start_time')"
              >开始时间</uni-th
            >
            <uni-th
              align="center"
              filter-type="timestamp"
              @filter-change="filterChange($event, 'end_time')"
              sortable
              @sort-change="sortChange($event, 'end_time')"
              >结束时间</uni-th
            >
            <uni-th
              align="center"
              @filter-change="filterChange($event, 'region_address')"
              @sort-change="sortChange($event, 'region_address')"
              >省/市/区</uni-th
            >
            <uni-th
              align="center"
              filter-type="search"
              @filter-change="filterChange($event, 'location_name')"
              sortable
              @sort-change="sortChange($event, 'location_name')"
              >活动地点</uni-th
            >
            <uni-th align="center">操作</uni-th>
          </uni-tr>
          <uni-tr v-for="(item, index) in data" :key="index">
            <uni-td v-if="isSuperAdmin" align="center">{{
              item.user_id
            }}</uni-td>
            <uni-td align="center">{{
              item.category_id &&
              item.category_id[0] &&
              item.category_id[0].text
            }}</uni-td>
            <uni-td align="center">略</uni-td>
            <uni-td align="center">略</uni-td>
            <uni-td align="center">{{
              options.article_status_valuetotext[item.article_status]
            }}</uni-td>
            <uni-td align="center">{{ item.title }}</uni-td>
            <uni-td align="center">
              <uni-dateformat
                :threshold="[0, 0]"
                :date="item.start_time"
              ></uni-dateformat>
            </uni-td>
            <uni-td align="center">
              <uni-dateformat
                :threshold="[0, 0]"
                :date="item.end_time"
              ></uni-dateformat>
            </uni-td>
            <uni-td align="center">{{
              converRegionAddress(item.region_address)
            }}</uni-td>
            <uni-td align="center">{{ item.location_name }}</uni-td>
            <uni-td align="center">
              <view class="uni-group">
                <button
                  @click="
                    navigateTo(
                      `./edit?id=${item._id}&provinces=${encodeURIComponent(
                        JSON.stringify(provinces)
                      )}`,
                      false
                    )
                  "
                  class="uni-button"
                  size="mini"
                  type="primary"
                  :disabled="!isSuperAdmin && item.article_status == 2"
                >
                  修改/详情
                </button>
                <button
                  @click="confirmDelete(item._id)"
                  class="uni-button"
                  size="mini"
                  type="warn"
                >
                  删除
                </button>
              </view>
            </uni-td>
          </uni-tr>
        </uni-table>
        <view class="uni-pagination-box">
          <uni-pagination
            show-icon
            :page-size="pagination.size"
            v-model="pagination.current"
            :total="pagination.count"
            @change="onPageChanged"
          />
        </view>
      </unicloud-db>
    </view>
  </view>
</template>

<script>
import {
  enumConverter,
  filterToWhere,
} from "@/js_sdk/validator/news-articles-image.js";

const db = uniCloud.database();
// 表查询配置
const dbOrderBy = ""; // 排序字段
const dbSearchFields = []; // 模糊搜索字段，支持模糊搜索的字段列表。联表查询格式: 主表字段名.副表字段名，例如用户表关联角色表 role.role_name
// 分页配置
const pageSize = 20;
const pageCurrent = 1;

const orderByMapping = {
  ascending: "asc",
  descending: "desc",
};

export default {
  data() {
    const isAdmin = this.$hasRole("admin");

    return {
      provinces: [], // 初始化为空数组
      collectionList: [
        db
          .collection("news-articles-image")
          .where(isAdmin ? {} : "user_id == $env.uid")
          .field(
            "user_id,category_id,avatar,content,article_status,last_comment_user_id,publish_date,last_modify_date,title,coupon_id,start_time,end_time,region_address,location_name,view_count,like_count,location_ip"
          )
          .getTemp(),
        db
          .collection("opendb-news-categories")
          .field("name as text, _id")
          .getTemp(),
      ],
      query: "",
      where: "",
      orderby: dbOrderBy,
      orderByFieldName: "",
      selectedIndexs: [],
      options: {
        pageSize,
        pageCurrent,
        filterData: {
          article_status_localdata: [
            {
              value: 0,
              text: "草稿箱",
            },
            {
              value: 1,
              text: "已发布",
            },
            {
              value: 2,
              text: "已过期",
            },
          ],
        },
        ...enumConverter,
      },
      imageStyles: {
        width: 64,
        height: 64,
      },
      exportExcel: {
        filename: "news-articles-image.xls",
        type: "xls",
        fields: {
          user_id: "user_id",
          分类: "category_id",
          活动简介: "avatar",
          活动详情: "content",
          活动状态: "article_status",
          last_comment_user_id: "last_comment_user_id",
          活动名称: "title",
          开始时间: "start_time",
          结束时间: "end_time",
          活动地点名称: "location_name",
        },
      },
      exportExcelData: [],
    };
  },
  onLoad() {
    this._filter = {};
    this.getGuangxiRegionData();
  },
  onReady() {
    this.$refs.udb.loadData();
  },
  computed: {
    isSuperAdmin() {
      return this.$hasRole("admin");
    },
  },
  methods: {
    converRegionAddress(regionAddress) {
      if (
        regionAddress &&
        regionAddress.text &&
        regionAddress.text.length === 3
      ) {
        return regionAddress.text.join("/");
      }
      return "无";
    },
    // 获取广西及其下辖市、区数据
    async getGuangxiRegionData() {
      const db = uniCloud.database();

      // 1. 获取广西省级数据
      const provinceRes = await db
        .collection("opendb-city-china")
        .where({
          name: "广西壮族自治区",
          type: 0,
        })
        .get();

      if (provinceRes.result.data.length === 0) {
        console.error("未找到广西壮族自治区数据");
        return null;
      }

      const guangxi = { ...provinceRes.result.data[0] };

      // 2. 获取广西下辖市级数据
      const citiesRes = await db
        .collection("opendb-city-china")
        .where({
          parent_code: guangxi.code,
          type: 1,
        })
        .get();

      guangxi.children = [...citiesRes.result.data];

      // 3. 获取每个市下辖的区级数据
      for (const city of guangxi.children) {
        const districtsRes = await db
          .collection("opendb-city-china")
          .where({
            parent_code: city.code,
            type: 2,
          })
          .get();

        city.children = [...districtsRes.result.data];
      }

      // console.log('广西完整地区数据:', guangxi);
      this.provinces = [guangxi];
    },
    onqueryload(data) {
      this.exportExcelData = data;
    },
    getWhere() {
      const query = this.query.trim();
      if (!query) {
        return "";
      }
      const queryRe = new RegExp(query, "i");
      return dbSearchFields
        .map((name) => queryRe + ".test(" + name + ")")
        .join(" || ");
    },
    search() {
      this.where = this.getWhere();
      this.$nextTick(() => {
        this.loadData();
      });
    },
    loadData(clear = true) {
      this.$refs.udb.loadData({
        clear,
      });
    },
    onPageChanged(e) {
      this.selectedIndexs.length = 0;
      this.$refs.table.clearSelection();
      this.$refs.udb.loadData({
        current: e.current,
      });
    },
    navigateTo(url, clear) {
      // clear 表示刷新列表时是否清除页码，true 表示刷新并回到列表第 1 页，默认为 true
      uni.navigateTo({
        url,
        events: {
          refreshData: () => {
            this.loadData(clear);
          },
        },
      });
    },
    // 多选处理
    selectedItems() {
      var dataList = this.$refs.udb.dataList;
      return this.selectedIndexs.map((i) => dataList[i]._id);
    },
    // 批量删除
    delTable() {
      this.$refs.udb.remove(this.selectedItems(), {
        success: (res) => {
          this.$refs.table.clearSelection();
        },
      });
    },
    // 多选
    selectionChange(e) {
      this.selectedIndexs = e.detail.index;
    },
    confirmDelete(id) {
      this.$refs.udb.remove(id, {
        success: (res) => {
          this.$refs.table.clearSelection();
        },
      });
    },
    sortChange(e, name) {
      this.orderByFieldName = name;
      if (e.order) {
        this.orderby = name + " " + orderByMapping[e.order];
      } else {
        this.orderby = "";
      }
      this.$refs.table.clearSelection();
      this.$nextTick(() => {
        this.$refs.udb.loadData();
      });
    },
    filterChange(e, name) {
      this._filter[name] = {
        type: e.filterType,
        value: e.filter,
      };
      this.where =
        Object.keys(this.where).length ??
        filterToWhere(this._filter, db.command);
      this.$nextTick(() => {
        this.$refs.udb.loadData();
      });
    },
  },
};
</script>

<style></style>
